﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class OC_InfoUIWithScroll : RecieaveInputObject
{
    public static OC_InfoUIWithScroll instance;

    const int ListNum = 5;
    const float ListGap = 118.0f;
    const float PopupGap = 330.0f;
    const float ScrollFirstItemOrizninY = 288.0f;
    const float ScrollViewOrizinY = 0.0f;
    const float ScrollViewOrizinOffsetY = 200.0f;

    Transform[] m_InfoList;

    int m_PreSelectListNum = -1;
    public int m_SelectListNum = -1;

    bool m_IsOffsetMoving = false;
    float m_OffsetGoal = 0;
    float m_OffsetCrr = 0;
    float m_OffsetTime = 0;
    float m_TimeGap = 0;

    MemberModel m_Model;

    List<GameObject> m_GreenRoot = new List<GameObject>(); //그린 스텟 루트

	public override void AwakeObject()
    {
        UIScrollView sv = GetComp("UIScrollView") as UIScrollView;
        if (sv == null)
            sv = AddComp("UIScrollView") as UIScrollView;

        m_InfoList = new Transform[ListNum];

        for (int i = 0; i < ListNum; i++)
        {
            m_InfoList[i] = transform.Find(string.Format("infoList0{0}", i + 1));          
        }

        m_Cam = GameObject.Find("UI Root/Camera").camera;

        instance = this;
    }

    // 스크롤뷰 이동 끝난후 터치 인식
    void EndOfScrollViewMoving()
    {
        isAbleTouch = true;

        UIScrollView sv = GetComp("UIScrollView") as UIScrollView;
        sv.restrictWithinPanel = true; 
    }
   
    // 스크롤뷰 이동 트윈후에 불리는 함수 (스크롤뷰 오프셋 수정 마무리)
    void EndOffsetMoveTo()
    {        
        m_IsOffsetMoving = false;
        EndOfScrollViewMoving();
    }

    // 스크롤뷰 이동 트윈중에 동작하는 함수 (스크롤뷰 오프셋 수정)
    void OffsetMove()
    {        
        UIScrollView sv = GetComp("UIScrollView") as UIScrollView;
        SpringPanel sp = GetComponent("SpringPanel") as SpringPanel;
        if (sp != null)
            sp.enabled = false;

        UIPanel up = GetComp("UIPanel") as UIPanel;
        Vector2 offSet = up.clipOffset;
        offSet.y = ScrollViewOrizinOffsetY - sv.transform.localPosition.y + ScrollViewOrizinY;
        up.clipOffset = offSet;
    }

    public override void UpdateObject()
    { 
        if (m_IsOffsetMoving)
            OffsetMove();
    }

    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {       
        switch (collider.gameObject.name)
        {
            case "Button_Trait_open":
                {                                           
                    for (int i = 0; i < ListNum; i++)
                    {
                        if (m_InfoList[i] == collider.transform.parent.parent)
                        {
                            m_PreSelectListNum = m_SelectListNum;
                            m_SelectListNum = i;
                            break;
                        }
                    }     

                    MoveList();
                }
                break;
            case "Button_Trait_close":
                {                
                    m_SelectListNum = -1;
                    MoveList();
                }
                break;
        }
    }

    public void MoveList()
    {
        isAbleTouch = false;  // 터치 제한

        UIScrollView sv = GetComp("UIScrollView") as UIScrollView;
        UIPanel up = GetComp("UIPanel") as UIPanel;

        if (m_SelectListNum == -1)
        {
            for (int i = 0; i < ListNum; i++)
            {
                m_InfoList[i].Find("open").gameObject.SetActive(false);
                m_InfoList[i].Find("close").gameObject.SetActive(true);

                if (m_InfoList[i].gameObject.activeSelf)
                    iTween.MoveTo(m_InfoList[i].gameObject, iTween.Hash("islocal", true, "y", ScrollFirstItemOrizninY  - ((i * ListGap)), "time", 0.5f));               
                else
                {
                    Vector3 pos = m_InfoList[i].transform.localPosition;
                    pos.y = ScrollFirstItemOrizninY - ((i * ListGap));
                    m_InfoList[i].transform.localPosition = pos;
                }
            }

            iTween.MoveTo(sv.gameObject, iTween.Hash("islocal", true, "y", ScrollViewOrizinY, "time", 0.5f
                , "oncompletetarget", gameObject, "oncomplete", "EndOffsetMoveTo"));
           
            m_IsOffsetMoving = true;
            sv.restrictWithinPanel = false; 
        }
        else
        {
            if (m_PreSelectListNum != m_SelectListNum)
            {
                for (int i = 0; i < ListNum; i++)
                {
                    m_InfoList[i].Find("open").gameObject.SetActive(false);
                    m_InfoList[i].Find("close").gameObject.SetActive(true);

                    if (i > m_SelectListNum)
                    {
                        if (m_InfoList[i].gameObject.activeSelf)
                            iTween.MoveTo(m_InfoList[i].gameObject, iTween.Hash("islocal", true, "y", ScrollFirstItemOrizninY - ((i * ListGap) + PopupGap), "time", 0.5f));
                        else
                        {
                            Vector3 pos = m_InfoList[i].transform.localPosition;
                            pos.y = ScrollFirstItemOrizninY - ((i * ListGap) + PopupGap);
                            m_InfoList[i].transform.localPosition = pos;
                        }
                    }
                    else
                    {
                        if (m_InfoList[i].gameObject.activeSelf)
                            iTween.MoveTo(m_InfoList[i].gameObject, iTween.Hash("islocal", true, "y", ScrollFirstItemOrizninY - ((i * ListGap)), "time", 0.5f));
                        else
                        {
                            Vector3 pos = m_InfoList[i].transform.localPosition;
                            pos.y = ScrollFirstItemOrizninY - ((i * ListGap));
                            m_InfoList[i].transform.localPosition = pos;
                        }
                    }
                }

                StartCoroutine("PopMenu");

                iTween.MoveTo(sv.gameObject, iTween.Hash("islocal", true, "y", ScrollViewOrizinY + (ListGap * m_SelectListNum), "time", 0.5f, "oncompletetarget", gameObject, "oncomplete", "EndOffsetMoveTo"));
               
                m_IsOffsetMoving = true;
                sv.restrictWithinPanel = false; 
            }
        }

        if (m_Model != null)
            UpdateStats(m_Model);
    }

    IEnumerator PopMenu()
    {
        yield return new WaitForSeconds(0.5f);

        m_InfoList[m_SelectListNum].Find("close").gameObject.SetActive(false);
        m_InfoList[m_SelectListNum].Find("open").gameObject.SetActive(true);
    }


    public void UpdateInfoUI(MemberModel tempModel)
    {
        m_Model = tempModel;

        Transform infoSubjectTR = transform.parent.Find("Point");
        UILabel allPointLabel = infoSubjectTR.Find("allPoint").GetComponent("UILabel") as UILabel;
        //allPointLabel.text = string.Format("{0} P", tempModel.maxTraitPoint);
        UILabel t_Label = infoSubjectTR.Find("point").GetComponent("UILabel") as UILabel;
        t_Label.text = string.Format("{0} / {1}P", tempModel.traitPoint, tempModel.maxTraitPoint);
        t_Label.MakePixelPerfect();

        int ListNum = 5;
        Transform infoList = null;
        Transform onOff = null;

        
        //UILabel pointLabel 위선언 재활용
        for (int i = 0; i < ListNum; i++)
        {
            infoList = transform.Find(string.Format("infoList0{0}", i + 1));

            if (tempModel.traits[i] != 0)
            {
                onOff = infoList.Find("close");
                t_Label = onOff.Find("point").GetComponent("UILabel") as UILabel;
                t_Label.text = string.Format("{0}P", tempModel.traitLevels[i]);

                t_Label = onOff.Find("name").GetComponent("UILabel") as UILabel;
                t_Label.text = TextController.GetStringWithId(string.Format("trait{0}", tempModel.traits[i]));
                t_Label.width = 0;
                t_Label.height = 0;
                t_Label.MakePixelPerfect();
                Vector3 pos = t_Label.transform.localPosition;
                pos.x = -360.0f;
                pos.y = 1.0f;
                t_Label.transform.localPosition = pos;

                float nameSize = t_Label.width;

                t_Label = onOff.Find("explain").GetComponent("UILabel") as UILabel;

                string keyValue = null;
                if (tempModel.traits[i] / 100 > 0)
                    keyValue = "uiCommonTextFeature";
                else if (tempModel.traits[i] < 11)
                    keyValue = "uiCommonTextRace";
                else
                    keyValue = "uiCommonTextClass";

                t_Label.text = TextController.GetStringWithId(keyValue);
                t_Label.MakePixelPerfect();
                pos = t_Label.transform.localPosition;
                pos.x = -320.0f + nameSize;
                pos.y = -9.0f;
                t_Label.transform.localPosition = pos;

                UISprite icon = onOff.Find("Icon").Find("info_icon_01").GetComponent("UISprite") as UISprite;
                icon.spriteName = tempModel.traits[i].ToString();

                onOff = infoList.Find("open");
                t_Label = onOff.Find("point").GetComponent("UILabel") as UILabel;
                t_Label.text = string.Format("{0}P", tempModel.traitLevels[i]);

                t_Label = onOff.Find("name").GetComponent("UILabel") as UILabel;
                t_Label.text = TextController.GetStringWithId(string.Format("trait{0}", tempModel.traits[i]));
                t_Label.width = 0;
                t_Label.height = 0;
                t_Label.MakePixelPerfect();
                pos = t_Label.transform.localPosition;
                pos.x = -360.0f;
                pos.y = 156.0f;
                t_Label.transform.localPosition = pos;

                nameSize = t_Label.width;

                t_Label = onOff.Find("explain").GetComponent("UILabel") as UILabel;
                t_Label.text = TextController.GetStringWithId(keyValue);
                t_Label.MakePixelPerfect();
                pos = t_Label.transform.localPosition;
                pos.x = -320.0f + nameSize;
                pos.y = 146.0f;
                t_Label.transform.localPosition = pos;

                t_Label = onOff.Find("enhanceExplain").GetComponent("UILabel") as UILabel;

                t_Label.text = TextController.GetStringWithId(string.Format("traitText{0}", tempModel.traits[i]));
                //t_Label.MakePixelPerfect();

                icon = onOff.Find("Icon").Find("info_icon_01").GetComponent("UISprite") as UISprite;
                icon.spriteName = tempModel.traits[i].ToString();

                infoList.gameObject.SetActive(true);
            }
            else
            {
                infoList.gameObject.SetActive(false);
            }
        }

        if (m_Model != null)
            UpdateStats(m_Model);

        ////인포 버튼 컨트롤

        Transform CharacterInfoBtn = transform.parent.Find("CharacterInfo");

        if (CharacterInfoBtn.gameObject.activeSelf)
        {
            Transform btn = CharacterInfoBtn.Find("btn").Find("Button_Dismiss");
            EPButton eb = btn.GetComponent("EPButton") as EPButton;
            eb.isEnabled = !tempModel.IsSelected;
        }
    }


    // 인포 패널에 보여지는 순서
    AptitudeID_New[] m_ShowOrder = new AptitudeID_New[6]
    {
        AptitudeID_New.baseAtk,
        AptitudeID_New.taunt,
        AptitudeID_New.init,
        AptitudeID_New.baseDef,
        AptitudeID_New.assist,
        AptitudeID_New.baseHP,
    };

    //5개 로컬라이제이션 키값
    string[] atkName = new string[5] { "combatAtkType1", "combatAtkType2", 
                    "combatAtkType3", "combatAtkType4", "combatAtkType5" };

    void UpdateStats(MemberModel tempModel)
    {      
        DBaseCharacter_New stats = tempModel.m_Stat.data;

        Transform statText = transform.parent.Find("StatText");
        UILabel statLabel = null;

        List<int> effectIndex = new List<int>();

        if (m_SelectListNum != -1)
        {
            DTrait traitInfo = GameData.Inst.GetTrait(tempModel.traits[m_SelectListNum]);

            if (traitInfo != null)
            {
                effectIndex.Add(traitInfo.effStat1);
                effectIndex.Add(traitInfo.effStat2);
                effectIndex.Add(traitInfo.effStat3);
            }
            else
                Debug.LogError("UpdateStats error");

            effectIndex.RemoveAll(is0);
        }

        m_GreenRoot.Clear();

        UILabel StatName = null;
        for (int i = 0; i < m_ShowOrder.Length; i++)
        {
            statLabel = statText.Find(string.Format("Stat{0:00}", i)).Find("text").GetComponent("UILabel") as UILabel;
            StatName = statText.Find(string.Format("Stat{0:00}", i)).Find("statname").GetComponent("UILabel") as UILabel;
            
            if (i == 0)
            {  
                StatName.text = string.Format("{0:#,0}", TextController.GetStringWithId(atkName[stats.atkType - 1]));                
            }

            bool isGreen = false;
            if (effectIndex.Count > 0)
            {
                foreach (int index in effectIndex)
                {                    
                    if ((int)m_ShowOrder[i] == index)
                    {
                        isGreen = true;
                        break;
                    }
                }                    
            }
            int effValue = 0;
            if (tempModel.leftItem != null)
            {
                if (tempModel.leftItem.itemInfo.effectType1 == (int)m_ShowOrder[i])
                    effValue += tempModel.leftItem.effectValue01;

                if (tempModel.leftItem.itemInfo.effectType2 == (int)m_ShowOrder[i])
                    effValue += tempModel.leftItem.effectValue02;
            }

            if (tempModel.rightItem != null)
            {
                if (tempModel.rightItem.itemInfo.effectType1 == (int)m_ShowOrder[i])
                    effValue += tempModel.rightItem.effectValue01;

                if (tempModel.rightItem.itemInfo.effectType2 == (int)m_ShowOrder[i])
                    effValue += tempModel.rightItem.effectValue02;
            }               

            //if (effValue > 0)
            //{                    
            //    statLabel.text = string.Format("{0}  [55cff9](+{1})[-]", statLabel.text, effValue);
            //}

            if (isGreen)
            {
                m_GreenRoot.Add(statLabel.transform.parent.gameObject);
                statLabel.text = string.Format("[7eff00]{0:#,0}[-]", stats[m_ShowOrder[i]]);
                StatName.text = StatName.text.Insert(0, "[7eff00]");
                StatName.text = StatName.text.Insert(StatName.text.Length, "[-]");

                if (effValue > 0)
                    statLabel.text = string.Format("[7eff00]{0:#,0}  (+{1})[-]", stats[m_ShowOrder[i]], effValue);
                else
                    statLabel.text = string.Format("[7eff00]{0:#,0}[-]", stats[m_ShowOrder[i]]);
            }
            else
            {
                statLabel.text = string.Format("{0:#,0}", stats[m_ShowOrder[i]]);
                StatName.text = StatName.text.Replace("[7eff00]", "");
                StatName.text = StatName.text.Replace("[-]", "");

                if (effValue > 0)
                {
                    statLabel.text = string.Format("{0}  [55cff9](+{1})[-]", statLabel.text, effValue);
                }
            }            
        }
    }

    public void StatTextAniPlay()
    {
        float scale = 1.1f;
       
        foreach(GameObject t in m_GreenRoot)
        {            
            t.transform.localScale = Vector3.one;
            iTween.ScaleTo(t, iTween.Hash("islocal", true, "scale", new Vector3(scale, scale, 1), "time", 0.2f, "looptype", "loop"));
        }

        StartCoroutine("stopLoop", 0.2f);
    }

    IEnumerator stopLoop(float time)
    {
        yield return new WaitForSeconds(time);
        
        foreach (GameObject t in m_GreenRoot)
        {            
            iTween.Stop(t);
            t.transform.localScale = Vector3.one;
        }
    }

    bool is0(int i)
    {
        return (i == 0);
    }
}